//
//  PlayViewModel.swift
//  ImGuider X
//
//  Created by 王鹏宇 on 10/9/18.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

enum MenuType {
    case MenuTypeMap
    case MenuTypeCamera
    case MenuTypeSearch
    case MenuTypeNode
    case MenuTypeKeyboard
    case MenuTypeList
}

enum SearchResultType {
   case NoResult
   case GetResult
   case MaybeResult
}
class PlayViewModel: NSObject {
    
    
    deinit {
        
        stopAutoplayTimer()
        stopDrawTimer()
    }
    
    var lineid:String?
    
    var menuTagsArray:[MenuType] = [.MenuTypeMap,.MenuTypeCamera,.MenuTypeSearch,.MenuTypeNode]
    
    var currentRecord : Record? {
        
        didSet {
            
            reloadRecord?()
        }
    }
    var currentIndexPath : IndexPath = IndexPath(row: 0, section: 0)
    var currentIndex : Int = 0
    var loadFinished:((String?)-> Void)?
    
    var reloadRecord:(()->Void)?
    var searchRelod:((SearchResultType)->Void)?
    
    var reloadMapFinished:(()-> Void)?
    var lastMapviewIndex:Int?
    var mapDrawLineAction:(()->Void)?
    
    var autoPlayAction:((_ ann:TripAnnotion,_ alert:Bool)->Void)?
    
    var line: Line? {
        
        didSet {
            
            WPY_AVPlayer.playManager.musicArray = records ?? []
            WPY_AVPlayer.playManager.lineModel = line
            
            currentRecord = line?.records?.first
            self.filterMenu()
        }
    }
    
    var currentPics:[String]? {
        
        return currentRecord?.pictureArray
    }
    var records:[Record]? {
        
        if var records = line?.records,records.count > 1 {
            
//            去掉试听的点
            records.remove(at: 0)
            return records
        }
        return nil
    }
    
    var resultArray:[Record]?
    
    func reloadData() {
        
        guard let lineid = lineid else {
            
            loadFinished?(LocalizedString("analysis_error"))
            return
        }
        
        if let line =  DownloadManager.share.hasTappedDownload(lineid: lineid) {
            
            self.line = line
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) {
                [weak self] in
                guard let `self` = self else { return }
                
                self.initDownload()
                self.loadFinished?(nil)
            }
            
            return
        }
        
        NetAPI.lineinfo(lineid: lineid).request(Line.self) {
            
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            if let line = response as? Line {
                
                self.line = line
            }
            self.loadFinished?(errmsg)
        }
    }
    
    
//    ----------------------下载---------------------------
    
    
    var progressText:((String) ->Void)?
    
    var hasDownload:Bool = false
    var downloadComplete:Bool = false
    
    var refreshCollectionView:(()->Void)?
    
    func downloadTapped() {
        
        if downloadComplete {
            
            return
        }
        
        guard let line = line else {
            
            return
        }
        
        if line.bought == false {
            
            self.progressText?("没买过，下载个毛线")
            return
        }
        
        self.progressText?("等待")
        self.hasDownload = true
        
        self.refreshCollectionView?()
        
        DownloadManager.share.startLineDown(line: line)
        
        DownloadManager.share.progress(lineid: line.lineid!) {
            [weak self] complete, suc, progress in
            guard let `self` = self else { return }
            
            if complete {
                
                if suc {
                    
                    self.progressText?("成功")
                    self.downloadComplete = true
                } else {
                    
                    self.progressText?("重试")
                }
                
                self.refreshCollectionView?()
                return
            }
            
            if (progress.isNaN || progress.isInfinite){
                return
            }
            
            let text = "\(Int(progress * 100))%"
            self.progressText?(text)
        }
    }
    
    private func initDownload() {
        
        guard let line = line else {
            
            self.progressText?("下载")
            
            return
        }
        
        self.hasDownload = true
        
        let status = DownloadManager.share.downloadStatus(lineid: line.lineid!)
        
        switch status {
            
        case .suspend:
            
            self.progressText?("暂停")
        case .failed:
            
            self.progressText?("重试")
        case .running:
            
            downloadTapped()
        case .completed:
            
            self.progressText?("成功")
            self.downloadComplete = true
            
        default:
            
            self.progressText?("错误，可能没买过")
            return
        }
        
    }
    
    func filterMenu(){
        
        if !(self.line?.hasmap ?? false) {
            
            if let index = self.menuTagsArray.firstIndex(of: MenuType.MenuTypeMap) {
                 self.menuTagsArray.remove(at: index)
                }
        }
        
        if !(self.line?.hascode ?? false) {
            
            if let index = self.menuTagsArray.firstIndex(of: MenuType.MenuTypeNode) {
                self.menuTagsArray.remove(at: index)
            }
        }else{
            if let index = self.menuTagsArray.firstIndex(of: MenuType.MenuTypeSearch) {
                self.menuTagsArray.remove(at: index)
            }
        }
        
        if !(self.line?.cansearch ?? false) {
            
            if let index = self.menuTagsArray.firstIndex(of: MenuType.MenuTypeSearch) {
                self.menuTagsArray.remove(at: index)
            }
        }
    }
    
    func cellDownloadText(playpath:String,block:@escaping (_ proText:String,_ playpath:String)->Void) {
        
        guard let lineid = lineid else {
        
            block("", playpath)
            return
        }
        
        let status = DownloadManager.share.downloadStatus(lineid: lineid,playpath: playpath)
        
        switch status {
            
        case .suspend:
            
            block("暂停", playpath)
            return
        case .failed:
            
            block("失败，请重试", playpath)
            return
            
        case .completed:
            
            block("下载成功", playpath)
            return
            
        default:
            
            break
        }
        
        DownloadManager.share.progress(lineid: lineid, playpath: playpath) { (complete, suc, progress) in
            
            if complete {
                
                if suc {
                    
                    block("下载成功", playpath)
                } else {
                    
                    block("失败", playpath)
                }
                
                return
            }
            
            block("下载进度：\(String(format: "%.2f", progress * 100))%", playpath)
        }
    }
    
    
    func searchNodeNumberWith(searchText : String) {
    
        if searchText.count <= 2 {
            
            return
        }
        
        let predicate = NSPredicate(format: "SELF  BEGINSWITH[dd] %@",searchText)
        
        print(searchText)
        let arr  = self.records?.filter({ record in
    
            guard let num = record.nodenumber else {return false}
            
            let flag = predicate.evaluate(with: num)
            return  flag }) ?? []
        
        if arr.count > 0 {
            
            self.resultArray = arr
            self.searchRelod?(.GetResult)
        }else {
            
            self.resultArray = self.getMayBeResultWith(searchTest: searchText)
            if let cout = self.resultArray?.count {
                if cout > 0 {
                    self.searchRelod?(.MaybeResult)
                }else{
                    self.searchRelod?(.NoResult)
                }
            }else{
                self.searchRelod?(.NoResult)
            }
        }
    }
    
    func getMayBeResultWith(searchTest : String)-> Array<Record>{
        
        var  predicate = NSPredicate(format: "SELF  LIKE %@",searchTest)
        
        let endIndex1 = searchTest.index(searchTest.startIndex, offsetBy: 1)

        let  Str1 = searchTest.replacingCharacters(in: searchTest.startIndex..<endIndex1, with: "?")
        
        
        let endIndex2 = searchTest.index(endIndex1, offsetBy:1)
        let Str2 = searchTest.replacingCharacters(in: endIndex1..<endIndex2, with: "?")
        
        let endIndex3 = searchTest.index(endIndex2, offsetBy:1)
        let Str3 = searchTest.replacingCharacters(in: endIndex2..<endIndex3, with: "?")
        
        if (searchTest.count == 3){
            
            predicate = NSPredicate(format:"SELF  LIKE %@ || SELF  LIKE %@ || SELF  LIKE %@", Str1,Str2,Str3)
        }else if(searchTest.count == 4){
            
            let endIndex4 = searchTest.index(endIndex3, offsetBy:1)
            let Str4 = searchTest.replacingCharacters(in: endIndex3..<endIndex4, with: "?")
            
            predicate = NSPredicate(format:"SELF  LIKE %@ || SELF  LIKE %@ || SELF  LIKE %@ || SELF  LIKE %@", Str1,Str2,Str3,Str4)
        }else if (searchTest.count == 5){
            
            let endIndex4 = searchTest.index(endIndex3, offsetBy:1)
            let Str4 = searchTest.replacingCharacters(in: endIndex3..<endIndex4, with: "?")
            
            let endIndex5 = searchTest.index(endIndex4, offsetBy:1)
            
            let Str5 = searchTest.replacingCharacters(in: endIndex4..<endIndex5, with: "?")
            
            predicate = NSPredicate(format:"SELF  LIKE %@ || SELF  LIKE %@ || SELF  LIKE %@ || SELF  LIKE %@ || SELF  LIKE %@", Str1,Str2,Str3,Str4,Str5)
        }
        
        
        let arr = self.records?.filter({ record in
            
            guard let num = record.nodenumber else {return false}
            
            let flag = predicate.evaluate(with: num)
            return  flag }) ?? []
    
        return arr
    }
}
